package megrez.mail.sender.component;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import megrez.mail.sender.common.MailMessage;
import megrez.mail.sender.common.MailSenderBean;
import megrez.mail.sender.common.MailSenderService;
import megrez.mail.sender.component.template.TemplateProcessFactory;
import megrez.mail.sender.domain.MailContentType;
import megrez.mail.sender.domain.QueryService;
import megrez.mail.sender.domain.TemplateConfig;
import megrez.mail.sender.domain.TemplateContent;

/**
 * 邮件发送组件
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MailSenderComponent {
    private final QueryService querySrc;
    private final TemplateProcessFactory templateProcessFactory;
    private final MailSenderService mailSenderSrc;

    public void send(MailMessage message) {
        message.validate();

        if (log.isDebugEnabled()) {
            log.debug("Mail message: {}", message);
        }

        TemplateConfig templateConfig = querySrc.findConfigByCode(message.getTemplateCode());
        if (!Boolean.TRUE.equals(templateConfig.getEnabled())) {
            // 禁用，不发送邮件
            log.warn("Tempate config is disabled");
            return;
        }
        TemplateContent templateContent = querySrc.findContent(templateConfig, message.getLocale());
        if (!StringUtils.hasText(templateContent.getData())) {
            log.warn("Tempate content is empty, action aborted");
            return;
        }

        // 创建发送对象
        MailSenderBean bean = new MailSenderBean();
        bean.setSubject(StringUtils.hasText(message.getSubject()) ? message.getSubject() : templateContent.getSubject());
        bean.getMailAddresses().addAll(message.getMails());
        MailContentType type = templateConfig.getType();
        bean.setTextable(type.isText());
        Map<String, Object> params = new HashMap<>();
        params.putAll(message.getParamters());
        
        // 处理发送文本
        String body = templateProcessFactory.getProcess(type).render(templateContent.getData(), params);
        bean.setBody(body);

        mailSenderSrc.send(bean);

        if (log.isDebugEnabled()) {
            log.debug("Mail sent successfully：{}", bean);
        }
    }
}
